#include "minimalmemorymanager.h"
// 简化的统一缓存加载服务实现
SimpleCacheLoadingService::LoadResult SimpleCacheLoadingService::loadFromCache(const QString& fileIdentity, int pageIndex) {
    LoadResult result;
    result.loadTime = QDateTime::currentDateTime();
    try {
        // 直接使用已验证工作的UnifiedCacheManager
        QImage image = UnifiedCacheManager::instance()->loadFromCache(fileIdentity, pageIndex);
        if (!image.isNull()) {
            result.image = image;
            result.success = true;
            result.memoryUsed = image.sizeInBytes();
            return result;
        }
        // 如果UnifiedCacheManager失败，回退到直接文件加载
        QString cacheKey = FileIdentityManager::getCacheKey(fileIdentity);
        QString cacheDir = UnifiedCacheManager::instance()->getCacheDirectory() + "/" + cacheKey;
        QString fileName = QString("page_%1.png").arg(pageIndex, 5, 10, QChar('0'));
        QString filePath = cacheDir + "/" + fileName;
        // 添加详细调试信息
        if (QFile::exists(filePath)) {
            QImage image(filePath);
            if (!image.isNull()) {
                result.image = image;
                result.success = true;
                result.memoryUsed = image.sizeInBytes();
            } else {
                result.errorMessage = "Image file corrupted";
            }
        } else {
            result.errorMessage = QString("Cache file not found: %1").arg(filePath);
            // 检查目录是否存在
            QDir dir(cacheDir);
            if (dir.exists()) {
                QStringList allFiles = dir.entryList(QDir::Files);
                if (allFiles.size() <= 10) {  // 只显示前10个文件
                }
            } else {
            }
        }
    } catch (const std::exception& e) {
        result.errorMessage = QString("Exception: %1").arg(e.what());
    }
    return result;
}
bool SimpleCacheLoadingService::isCacheAvailable(const QString& fileIdentity, int pageIndex) const {
    QString cacheKey = FileIdentityManager::getCacheKey(fileIdentity);
    QString cacheDir = UnifiedCacheManager::instance()->getCacheDirectory() + "/" + cacheKey;
    QString fileName = QString("page_%1.png").arg(pageIndex, 5, 10, QChar('0'));
    QString filePath = cacheDir + "/" + fileName;
    return QFile::exists(filePath);
}
// 支持缩略图的加载
SimpleCacheLoadingService::LoadResult SimpleCacheLoadingService::loadThumbnailFromCache(const QString& fileIdentity, int pageIndex) {
    LoadResult result;
    result.loadTime = QDateTime::currentDateTime();
    try {
        QString cacheKey = FileIdentityManager::getCacheKey(fileIdentity);
        QString cacheDir = UnifiedCacheManager::instance()->getCacheDirectory() + "/" + cacheKey;
        QString fileName = QString("thumb_%1.png").arg(pageIndex, 5, 10, QChar('0'));
        QString filePath = cacheDir + "/thumbnails/" + fileName;
        // 添加缩略图详细调试信息
        if (QFile::exists(filePath)) {
            QImage image(filePath);
            if (!image.isNull()) {
                result.image = image;
                result.success = true;
                result.memoryUsed = image.sizeInBytes();
            } else {
                result.errorMessage = "Thumbnail file corrupted";
            }
        } else {
            result.errorMessage = "Thumbnail cache file not found";
        }
    } catch (const std::exception& e) {
        result.errorMessage = QString("Thumbnail loading exception: %1").arg(e.what());
    }
    return result;
}
// 最小化统一内存管理器实现
MinimalUnifiedMemoryManager::MinimalUnifiedMemoryManager(QObject* mainWindow) 
    : m_mainWindow(mainWindow) {
    m_cacheService = std::make_unique<SimpleCacheLoadingService>();
}
void MinimalUnifiedMemoryManager::registerPool(ContentType type, size_t maxMemoryBytes) {
    // 简化实现：暂时不做实际管理
}
QImage MinimalUnifiedMemoryManager::getImage(ContentType type, int index, int currentFocus) {
    Q_UNUSED(currentFocus);
    // 根据内容类型选择正确的加载方法
    QString fileIdentity = getCurrentFileIdentity();
    SimpleCacheLoadingService::LoadResult result;
    if (type == ContentType::THUMBNAIL) {
        // 加载缩略图
        auto* service = static_cast<SimpleCacheLoadingService*>(m_cacheService.get());
        result = service->loadThumbnailFromCache(fileIdentity, index);
    } else {
        // 加载主图或组合页
        result = m_cacheService->loadFromCache(fileIdentity, index);
    }
    return result.success ? result.image : QImage();
}
void MinimalUnifiedMemoryManager::setCurrentFocus(ContentType type, int focus) {
    Q_UNUSED(type);
    Q_UNUSED(focus);
    // 简化实现：暂时不做处理
}
size_t MinimalUnifiedMemoryManager::getMemoryUsage(ContentType type) const {
    Q_UNUSED(type);
    return 0;  // 简化实现
}
void MinimalUnifiedMemoryManager::setMemoryStrategy(ContentType type, std::unique_ptr<IMemoryStrategy> strategy) {
    Q_UNUSED(type);
    Q_UNUSED(strategy);
    // 简化实现：暂时不做处理
}
void MinimalUnifiedMemoryManager::setCurrentFileIdentity(const QString& fileIdentity) {
    m_currentFileIdentity = fileIdentity;
}
QString MinimalUnifiedMemoryManager::getCurrentFileIdentity() const {
    // 优先使用设置的文件标识，这是最可靠的
    if (!m_currentFileIdentity.isEmpty()) {
        return m_currentFileIdentity;
    }
    // 尝试从MainWindow获取当前文件标识
    if (m_mainWindow) {
        QVariant result;
        bool success = QMetaObject::invokeMethod(m_mainWindow, "currentFileIdentity", 
                                               Qt::DirectConnection,
                                               Q_RETURN_ARG(QVariant, result));
        if (success && result.isValid()) {
            QString fileIdentity = result.toString();
            if (!fileIdentity.isEmpty()) {
                return fileIdentity;
            }
        }
    }
    // 最后回退到默认值
    return "default_file";
}
